﻿using System;
using AzureStorageMapper.Configurations;
using AzureStorageMapper.TableStorage.RESTCommunicate;
using AzureStorageMapper.TableStorage.Utils;
using AzureStorageMapper.TableStorage.ActionModes;

namespace AzureStorageMapper.TableStorage
{
    public abstract partial class TableEntity
    {
        private static TalkToTableStorage TalkToTableStorageProxy
        {
            get
            {
                CredentialElement credential = ConfigurationUtils.GetTableStroageCredential();
                return new TalkToTableStorage(credential.AccountName, credential.AccountKey);
            }
        }

        public string PartitionKey { get; set; }
        public string RowKey { get; set; }

        public TableEntity()
        {
        }

        public TableEntity(string partitionKey, string rowKey)
            : this()
        {
            PartitionKey = partitionKey;
            RowKey = rowKey;
        }
      
        public void Save(SaveMode mode = SaveMode.Insert)
        {            
            EntityInfo eInfo = TableUtilities.GetEntityInfo(this);
            TalkToTableStorageProxy.InsertEntity(eInfo, mode);
        }

        public void Update(UpdateMode mode = UpdateMode.Update)
        {
            EntityInfo eInfo = TableUtilities.GetEntityInfo(this);
            TalkToTableStorageProxy.UpdateEntity(eInfo, mode);
        }

        public void Delete()
        {
            EntityInfo eInfo = TableUtilities.GetEntityInfo(this);
            TalkToTableStorageProxy.DeleteEntity(eInfo.TableName, eInfo.PartitionKey, eInfo.RowKey);
        }
    }
}
